from umqtt.simple import MQTTClient
from machine import Pin
import network
import time

# mqtt 连接
client_id = "slim_id"
mserver = '192.168.1.101'
port=1883
username="user2"
password="pass2"

topic_ctl = b'ledSet'#设备订阅的主题,客户端推送消息的主题
topic_sta = b'ledPost'#客户端订阅的主题,设备推送消息的主题
client = None

led1=Pin(12, Pin.OUT, value=1)
led2=Pin(13, Pin.OUT, value=1)

# wifi 连接
wlan = network.WLAN(network.STA_IF) # create station interface
wlan.active(True)       # activate the interface
wlan.scan()             # scan for access points
wlan.isconnected()      # check if the station is connected to an AP
wlan.connect('501', '13048271212a') # connect to an AP
wlan.config('mac')      # get the interface's MAC address
wlan.ifconfig()         # get the interface's IP/netmask/gw/DNS addresses
    
def sub_callback(topic, msg):
    """
    收到订阅消息回调
    """
    global client
    print((topic_ctl, msg))
    if msg == b'led12/0':
        pub_msg = 'LED12: OFF-state'
        led1.value(0)
    elif msg == b'led12/1':
        pub_msg = 'LED12: ON-state'
        led1.value(1)
    elif msg == b'led13/0':
        pub_msg = 'LED13: OFF-state'
        led2.value(0)
    elif msg == b'led13/1':
        pub_msg = 'LED13: ON-state'
        led2.value(1)
    else:
        pub_msg = 'other msg'
    client.publish(topic_sta, pub_msg, retain=True)


try:
    print("mqtt中")
    client = MQTTClient(client_id, mserver, port, username,password)
    client.set_callback(sub_callback)
    client.connect()
    client.subscribe(topic_ctl)
    client.publish(topic_sta, 'ESP32 Device online', retain=True)
    print("Connected to %s, subscribed to %s topic" % (mserver, topic_ctl))
    while True:
        client.wait_msg()
finally:
   print("错误")


